'use client';

import trpc from '@/lib/trpc/client';
import type { Message } from '@/service/type/socket';
import { useState } from 'react';
import { Button } from '../ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import { Skeleton } from '../ui/skeleton';

const ReplyList = ({
  messages,
  onSend,
}: { messages: Message[]; onSend: (r: string) => void }) => {
  const { data, isLoading, error } = trpc.shop.genAiReply.useQuery(messages, {
    staleTime: Number.POSITIVE_INFINITY,
  });
  return (
    <div className="space-y-2 text-sm p-1">
      <p className="font-bold">选择回复：</p>
      {isLoading &&
        [1, 2, 3].map((i) => <Skeleton key={i} className="h-6 w-full" />)}
      {error && <p className="">生成回复失败</p>}
      {data?.map((r) => (
        <p
          className="hover:bg-muted cursor-pointer px-2 py-1 rounded"
          key={r}
          onClick={() => onSend(r)}
        >
          {r}
        </p>
      ))}
    </div>
  );
};

export default function AiReplyButton({
  messages,
  onSend,
}: { messages: Message[]; onSend: (r: string) => void }) {
  const [open, setOpen] = useState(false);
  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button>智能回复</Button>
      </PopoverTrigger>
      <PopoverContent side="top" sideOffset={10}>
        <ReplyList
          messages={messages}
          onSend={(r) => {
            setOpen(false);
            onSend(r);
          }}
        />
      </PopoverContent>
    </Popover>
  );
}
